﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using ImageUpload.Resources;
using Microsoft.Phone.Tasks;
using System.IO;
using System.Windows.Media.Imaging;

namespace ImageUpload
{
    public partial class MainPage : PhoneApplicationPage
    {
        PhotoChooserTask photoChooserTask;
        HttpWebRequest poster;
        byte[] array;
        string boundary = "----------" + DateTime.Now.Ticks.ToString();

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            photoChooserTask = new PhotoChooserTask();
            photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);

            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
        }

        private void LoadImage_Click(object sender, RoutedEventArgs e)
        {
            photoChooserTask.Show();
        }

        // Sample code for building a localized ApplicationBar
        //private void BuildLocalizedApplicationBar()
        //{
        //    // Set the page's ApplicationBar to a new instance of ApplicationBar.
        //    ApplicationBar = new ApplicationBar();

        //    // Create a new button and set the text value to the localized string from AppResources.
        //    ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
        //    appBarButton.Text = AppResources.AppBarButtonText;
        //    ApplicationBar.Buttons.Add(appBarButton);

        //    // Create a new menu item with the localized string from AppResources.
        //    ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
        //    ApplicationBar.MenuItems.Add(appBarMenuItem);
        //}

        // handle image selection
        void photoChooserTask_Completed(object sender, PhotoResult e)
        {
            Upload.IsEnabled = (e.TaskResult == TaskResult.OK);
            
            if (e.TaskResult == TaskResult.OK)
            {
                LogText.Text += "Image selected: " + e.OriginalFileName + "\r\n";

                // set preview image
                // conver my test pngs to jpg
                // get the byte array to be sent
                try
                {
                    BitmapImage image = new BitmapImage();
                    image.SetSource(e.ChosenPhoto);
                    Image.Source = image;

                    using (MemoryStream ms = new MemoryStream())
                    {
                        WriteableBitmap btmMap = new WriteableBitmap(image);

                        // write an image into the stream
                        Extensions.SaveJpeg(btmMap, ms, image.PixelWidth, image.PixelHeight, 0, 70);
                        array = ms.ToArray();
                    }
                }
                catch (ArgumentNullException) { /* Nothing */ }
            }
            else
            {
                LogText.Text += "No image selected.\r\n";
            }
        }

        // start the upload
        private void Upload_Click(object sender, RoutedEventArgs e)
        {
            LoadImage.IsEnabled = false;
            Upload.IsEnabled = false;
            Upload.Visibility = System.Windows.Visibility.Collapsed;
            Cancel.IsEnabled = true;
            Cancel.Visibility = System.Windows.Visibility.Visible;

            try
            {
                // test server for HTTP posts below
                // results are at http://posttestserver.com/data/<date>...
                // details at http://www.posttestserver.com/
                poster = WebRequest.Create(new Uri("http://posttestserver.com/post.php")) as HttpWebRequest;
                poster.UserAgent = "ImageUpload 1.0";
                poster.Method = "POST";
                poster.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);

                poster.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), poster);
            }
            catch (WebException we)
            {
                System.Diagnostics.Debug.WriteLine(we.Message);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            LoadImage.IsEnabled = true;
            Upload.IsEnabled = false;
            Upload.Visibility = System.Windows.Visibility.Visible;
            Cancel.IsEnabled = false;
            Cancel.Visibility = System.Windows.Visibility.Collapsed;
            LogText.Text = "";
        }

        // set POST's data
        private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            try
            {

            HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
            Stream postStream = request.EndGetRequestStream(asynchronousResult);

            //write boundries and section headers
            StreamWriter writer = new StreamWriter(postStream);
            writer.Write("--");
            writer.WriteLine(boundary);
            // make sure that "name" fields reflects form field as expected in your PHP
            writer.WriteLine(@"Content-Disposition: form-data; name=""file""; filename=""test1.jpg""");
            writer.WriteLine(@"Content-Type: image/jpeg");
            writer.WriteLine(@"Content-Length: " + array.Length);
            writer.WriteLine();
            writer.Flush();
            // write file's data
            postStream.Write(array, 0, array.Length);
            postStream.Flush();
            writer.WriteLine();
            // write final boundry
            writer.Write("--");
            writer.Write(boundary);
            writer.WriteLine("--");
            writer.Flush();
            postStream.Close();

            // Start the asynchronous operation to get the response
            request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
            }
            catch (WebException we)
            {
                System.Diagnostics.Debug.WriteLine(we.Message);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }

        // handle server's response
        private void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
                Stream streamResponse = response.GetResponseStream();
                StreamReader streamRead = new StreamReader(streamResponse);
                string responseString = streamRead.ReadToEnd();
                // Close the stream object
                streamResponse.Close();
                streamRead.Close();
                // Release the HttpWebResponse
                response.Close();

                this.Dispatcher.BeginInvoke(() =>
                {
                    LogText.Text += "Server response: " + responseString + "\r\n";
                    LoadImage.IsEnabled = true;
                    Upload.IsEnabled = false;
                    Upload.Visibility = System.Windows.Visibility.Visible;
                    Cancel.IsEnabled = false;
                    Cancel.Visibility = System.Windows.Visibility.Collapsed;
                });

            }
            catch (WebException we)
            {
#if _DEBUG
                Stream streamResponse = we.Response.GetResponseStream();
                StreamReader streamRead = new StreamReader(streamResponse);
                string responseString = streamRead.ReadToEnd();
                // Close the stream object
                streamResponse.Close();
                streamRead.Close();

                // log the detailed server response
                System.Diagnostics.Debug.WriteLine(responseString);
#endif
                this.Dispatcher.BeginInvoke(() =>
                {
                    LogText.Text += "Server response: " + we.Message + "\r\n";
                    LoadImage.IsEnabled = true;
                    Upload.IsEnabled = false;
                    Upload.Visibility = System.Windows.Visibility.Visible;
                    Cancel.IsEnabled = false;
                    Cancel.Visibility = System.Windows.Visibility.Collapsed;
                });
            }
        }

    }
}